package com.song.osclient;

import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.song.osclient.fragment.MenuFragment;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class MainActivity extends AppCompatActivity {
    @InjectView(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    ActionBarDrawerToggle toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(App.getCurrentTheme());
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        initDrawerLayout();
    }

    private void initDrawerLayout() {
        restoreActionBarIcon();
        toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.hello_world) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                changeActionBarIcon();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                restoreActionBarIcon();
            }
        };
        drawerLayout.setDrawerListener(toggle);
    }

    private void restoreActionBarIcon() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.mipmap.ic_drawer);
        }
       animateActionBarIcon();
    }

    private void changeActionBarIcon() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(0);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        animateActionBarIcon();
    }

    private void animateActionBarIcon(){
        drawerLayout.post(new Runnable() {
            @Override
            public void run() {
                toggle.syncState();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home){
            if (drawerLayout.isDrawerOpen(Gravity.LEFT)){
                drawerLayout.closeDrawer(Gravity.LEFT);
            }else {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
            return true;
        }else {
            return super.onOptionsItemSelected(item);
        }
    }
}
